<?php
/**
 * User: lsx
 * Date: 2017/6/1
 * Time: 14:32
 * Progress:0%
 */

namespace logic\wechat\index;


use library\common\str;
use library\common\wechat_msg\send_msg;
use library\tencent\wechat\admin_wechat\SendTemplateMessage;
use library\tencent\wechat\common\XmlUtils;
use library\tencent\wechat\wechat_index\PayManagement;
use model\Account;
use model\AccountBill;
use model\AccountPayment;
use model\AccountRechargeOrder;
use model\AccountRole;
use model\AccountWechat;
use model\ShopConfig;
use model\ShopGoods;
use model\ShopOrder;
use model\ShopOrderGoods;
use model\ShopOrderItem;
use model\ShopRegUserOrder;
use model\ShopUser;

use think\Config;
use think\Controller;
use think\Cookie;
use think\Db;

class LNotify extends Controller
{
    private $accountRechargeOrder;
    private $account;
    private $accountPayment;
    private $accountBill;
    private $pay;
    private $shopRegUserOrder;
    private $shopConfig;
    private $shopUser;
    private $shopOrder;
    private $shopOrderItem;
    private $shopGoods;
    private $shopOrderGoods;
    private $accountWechat;

    public function __construct()
    {
        parent::__construct();
        $this->account = new Account();
        $this->shopConfig = new ShopConfig();
        $this->shopRegUserOrder = new ShopRegUserOrder();
        $this->accountPayment = new AccountPayment();
        $this->accountBill = new AccountBill();
        $this->accountRechargeOrder = new AccountRechargeOrder();
        $this->shopUser = new ShopUser();
        $this->pay = PayManagement::instance();
        $this->shopOrder = new ShopOrder();
        $this->shopOrderItem = new ShopOrderItem();
        $this->shopGoods = new ShopGoods();
        $this->shopOrderGoods = new ShopOrderGoods();
        $this->accountWechat = new AccountWechat();
    }

    public function logic_wechat_pay_back($param)
    {
        $res = $this->pay->processNotification($param['xml']);
        $arr = $res['data'];

//        $arr = [
//            'out_trade_no' => "20170814175949820",
//            "attach" => 3
//        ];
        $type = $arr['attach'];
       //file_put_contents('./text1.txt', $type . '1111111111111111111', FILE_APPEND);
        switch ($type) {
            case 3://总订单微信支付
                $this->order_pay_affairs($arr);
                break;
            case 4://充值
               // file_put_contents('./text1.txt', $type . 'wwwwwwwwwww', FILE_APPEND);
                $this->recharge_pay_affairs($arr);
                break;
            case 5://子订单微信支付
                $this->order_items_pay_affairs($arr);
                break;
        }
    }


    //总订单支付事务
    private function order_pay_affairs($arr)
    {
        //更改payment记录
        $order = $this->shopOrder->where(['order_sn' => $arr['out_trade_no']])->find();
        if ($order->flag_pay==1){
            $this->pay->respond("支付成功", "OK");
        }
        $a_id = $order['account_id'];
        $pay_time = time();

        //插入钱帐记录
        Db::startTrans();
        $data3 = array(
            ['account_id' => $a_id, 'money' => $order['order_amount'], 'remark' => "总订单{$order->order_sn}-微信充值"],
            ['account_id' => $a_id, 'money' => 0 - $order['order_amount'], 'remark' => "总订单{$order->order_sn}-外卖消费"]
        );
        $res3 = $this->accountBill->saveAll($data3);
        if (!$res3) {
           // file_put_contents('./text2.txt', "错误1" . '<br/>', FILE_APPEND);
            $this->pay->respond(false, "数据出错5，请稍后再试");
            Db::rollback();
        }

        //找出子订单
        $order_items = ShopOrderItem::all(["order_id" => $order->id, "account_id" => $a_id]);
        $goods = [];
        foreach ($order_items as $v) {
           // $v->payment_id = $result->id;
            $v->flag_pay = 1;
            $v->pay_time = $pay_time;
            $result = $v->save();
            if (!$result) {
              //  file_put_contents('./text2.txt', "错误4" . '<br/>', FILE_APPEND);
                $this->pay->respond(false, "数据出错5，请稍后再试");
                Db::rollback();
            }
            $goods_id = $this->shopOrderGoods->where(["order_item_id"=>$v->id])->column("goods_id");
            $gn = $this->shopGoods->where(["id"=>["in",$goods_id]])->column("name");
            $goods = array_merge($goods,$gn);
        }
        $data = [
            "account_id" => $a_id,
            'pay_type' => 3,
            'pay_time' => $pay_time,
            "pay_no" => $order->order_sn,
            "pay_money" => $order->order_amount,
            "remark" => "订单({$order->order_sn})微信支付",
            'flag_pay' => 1,
            'flag_lock' => 1,
            'trade_no' => $arr['transaction_id'],
            'trade_time' => $arr['time_end'],
            'trade_money' => $arr['total_fee'] / 100
        ];

        $result = AccountPayment::create($data);
        if (!$result) {
         //   file_put_contents('./text2.txt', "错误3" . '<br/>', FILE_APPEND);
            $this->pay->respond(false, "数据出错5，请稍后再试");
            Db::rollback();
        }
        //更改订单支付状态
        $data4 = array(
            "payment_id"=>$result->id,
            'flag_pay' => 1,
            'pay_time' => $pay_time
        );
        $res4 = ShopOrder::update($data4,['id' => $order['id']]);
        if (!$res4) {
            //  file_put_contents('./text2.txt', "错误2" . '<br/>', FILE_APPEND);
            $this->pay->respond(false, "数据出错5，请稍后再试");
            Db::rollback();
        }
       // file_put_contents('./text2.txt', "成功" . '<br/>', FILE_APPEND);
        Db::commit();
        //消息模板

        $ar = new AccountRole();
        $acc_ids = $ar->where(["role_id"=>2,"flag_delete"=>0])->column("account_id");
        $oauths  = $this->accountWechat->where(["account_id"=>["in",$acc_ids]])->column("openid");
        send_msg::dispatching_msg($oauths, $order, $goods);
        $this->pay->respond("支付成功", "OK");
       // $this->success("支付成功", url('order/Pay/pay_success'));
    }

    //子订单支付事务
    private function order_items_pay_affairs($arr)
    {
        $order_item = $this->shopOrderItem->where(['order_sn' => $arr['out_trade_no']])->find();
        if ($order_item->flag_pay==1){
            $this->pay->respond("支付成功", "OK");
        }
        $a_id = $order_item['account_id'];
        $pay_time = time();
        $goods = [];
        Db::startTrans();
        //更改payment记录
        $data = [
            "account_id" => $a_id,
            'pay_type' => 3,
            'pay_time' => $pay_time,
            "pay_no" => $order_item->order_sn,
            "pay_money" => $order_item->order_amount,
            "remark" => "订单({$order_item->order_sn})微信支付",
            'flag_pay' => 1,
            'flag_lock' => 1,
            'trade_no' => $arr['transaction_id'],
            'trade_time' => $arr['time_end'],
            'trade_money' => $arr['total_fee'] / 100
        ];

        $res2 = AccountPayment::create($data);
        if (!$res2) {
            Db::rollback();
        }
        $data3 = array(
            ['account_id' => $a_id, 'money' => $order_item['order_amount'], 'remark' => "总订单{$order_item->order_sn}-充值"],
            ['account_id' => $a_id, 'money' => 0 - $order_item['order_amount'], 'remark' => "总订单{$order_item->order_sn}-消费"]
        );
        $res3 = $this->accountBill->saveAll($data3);
        if (!$res3) {
            $this->pay->respond(false, "数据出错5，请稍后再试");
            Db::rollback();
        }
        //更改订单支付状态
        $data4 = array(
            'flag_pay' => 1,
            'pay_time' => $pay_time,
        );
        $res4 = $this->shopOrderItem->save($data4, ['id' => $order_item['id']]);
        if (!$res4) {
            $this->pay->respond(false, "数据出错6，请稍后再试");
            Db::rollback();
        }

        $count = $this->shopOrderItem->where(["order_id" => $order_item->order_id, "flag_pay" => 1])->count();
        if ($count == 0) {
            $res5 = ShopOrder::update(["flag_pay" => 1, "pay_time" => $pay_time], ["id" => $order_item->order_id]);
            if (!$res5) {
                Db::rollback();
                $this->pay->respond(false, "数据出错7，请稍后再试");
            }
        }
        Db::commit();
        $goods_id = $this->shopOrderGoods->where(["order_item_id"=>$order_item->id])->column("goods_id");
        $gn = $this->shopGoods->where(["id"=>["in",$goods_id]])->column("name");
        $goods = array_merge($goods,$gn);
        //消息模板

        $ar = new AccountRole();
        $acc_ids = $ar->where(["role_id"=>2,"flag_delete"=>0])->column("account_id");
        $oauths  = $this->accountWechat->where(["account_id"=>["in",$acc_ids]])->column("openid");
        send_msg::dispatching_msg($oauths, $order_item, $goods);
        $this->pay->respond(true, "OK");
       // $this->pay->respond(url('order/Pay/pay_success'), "OK");
    }

    private function recharge_pay_affairs($arr)
    {
        //        回调事务开始
        $payment_item = $this->accountPayment->where(['pay_no' => $arr['out_trade_no']])->find();
        if ($payment_item["flag_pay"]==1){
            $this->pay->respond(true, "OK");
        }
        $account_id = $payment_item['account_id'];
        $pay_time = time();
        $total_fee = $arr['total_fee'] / 100;
//        修改充值记录
        Db::startTrans();

        $data0 = array(
            'pay_time' => $pay_time,
            'flag_pay' => 1,
            'flag_lock' => 1,
            'trade_no' => $arr['transaction_id'],
            'trade_time' => $arr['time_end'],
            'remark' => '充值成功',
            'trade_money' => $total_fee
        );

        $res0 = AccountPayment::update($data0,["pay_no"=>$arr['out_trade_no']]);
        if (!$res0) {
            Db::rollback();
           // file_put_contents('./text1.txt', 1 . '<br/>', FILE_APPEND);
            $this->pay->respond(false, "fail");
        }
        $data1 = array(
            "flag_pay"=>1
        );
        $res1 = AccountRechargeOrder::update($data1,["payment_id"=>$payment_item["id"]]);
        if (!$res1) {
            Db::rollback();
            // file_put_contents('./text1.txt', 1 . '<br/>', FILE_APPEND);
            $this->pay->respond(false, "fail");
        }
        // 插入钱帐记录
        $data2 = array(
            'account_id' => $account_id,
            'money' => $total_fee,
            'remark' => '外卖-账户充值'
        );
        $res2 = $this->accountBill->save($data2);
        if (!$res2) {
            Db::rollback();
         //  file_put_contents('./text1.txt', 2 . '<br/>', FILE_APPEND);
            $this->pay->respond(false, "fail");

        }
        //更改账户余额
        $res3 = $this->account->where(['id' => $account_id])->setInc('money',$total_fee);
        if (!$res3) {
            Db::rollback();
         //   file_put_contents('./text1.txt', 3 . '<br/>', FILE_APPEND);
            $this->pay->respond(false, "fail");
        }
        Db::commit();
        //file_put_contents('./text1.txt', "成功". '<br/>', FILE_APPEND);
        //消息模板
//        $oauth  = AccountWechat::get(['account_id' =>$a_id]);
//        $openid = $oauth['openid'];
//        $data = array(
//            'touser' => $openid,
//            'keyword2' => "充值成功",
//            'keyword3' => date('Y-m-d', $pay_time),
//            'keyword4' => "外卖",
//            'keyword5' => $total_fee . '元'
//        );
//        SendTemplateMessage::send_message("OPENTM204987032", $data);

        $this->pay->respond(true, "OK");
    }

}